import binascii,string,zipfile,os,re

from PySide6.QtWidgets import QApplication

from tools import config

def 单压缩包内CRC爆破(self):
    CRC_str = ""
    try:
        f = zipfile.ZipFile(config.file_name, "r")   # 读取单个文件
        self.ui.print_echo.append("开始执行CRC爆破")
        for i in range(0,len(f.filelist)):
            crc = f.filelist[i].CRC
            CRC_ASK_str = CRC_ASK(hex(crc))               # 获取CRC值
            self.ui.print_echo.append(f"第{i + 1}个CRC的值为:{CRC_ASK_str}")
            CRC_str += CRC_ASK_str
        self.ui.print_echo.append(f"最终结果为:{CRC_str}")
    except Exception as e:
        self.ui.print_echo.append(f'CRC读取失败,原因:{e}')
    config.清理目录(self)
def 多文件压缩包CRC爆破(self):
    
    CRC_str = ""
    try:
        self.ui.print_echo.append("开始执行CRC爆破")
        files = os.listdir(config.文件目录)   # 读取文件夹内所有文件                   # 计算文件个数
        self.设置进度.emit(len(files))
        files.sort(key= lambda x : int(re.findall('([0-9]+)',x)[0]))
        for i in range(0, len(files)):
            f = zipfile.ZipFile(config.文件目录 + files[i], "r") # 读取单个文件
            zipinfo = f.getinfo(" ".join(list(f.NameToInfo.keys())))    # 获取文件信息
            CRC_ASK_str = CRC_ASK(hex(zipinfo.CRC))               # 获取CRC值
            self.ui.print_echo.append(f"第{i + 1}个CRC的值为:{CRC_ASK_str}")
            QApplication.processEvents()
            CRC_str += CRC_ASK_str
            self.进度信号.emit(i + 1)
        self.输出信号.emit(f"最终结果为:{CRC_str}")
    except Exception as e:
        self.ui.print_echo.append('CRC爆破失败,原因:{}'.format(e))
    config.清理目录(self)
def CRC_ASK(crc):
    try:
        dic = (string.ascii_letters + string.digits + "+/=")  # 打印出字符表  string.ascii_letters + string.digits + '+/='
        for a in dic:
            for b in dic:
                for c in dic:
                    for d in dic:
                        s = a + b + c + d
                        s = str(s).encode()
                        if crc == hex(binascii.crc32(s)):
                            return s.decode("utf-8")
    except Exception as e:
        print("CRC爆破失败,原因:{}".format(e))

def 伪加密(self):
    self.ui.print_echo.append("尝试破解伪加密")
    try:
        data = config.文件读取(self)
        data = bytearray(data)
        index = data.find(b'PK\x03\x04')   #  504B0304后的第3、4个byte改成0000
        if not index:
            i = index + 4
            data[i + 2:i + 4] = b'\x00\x00'
        index1 = data.find(b'PK\x01\x02')  #  504B0102后的第5、6个byte改成0000
        if index1:
            i = index1 + 4
            data[i + 4:i + 6] = b'\x00\x00'
        # 将修改后的十六进制文件 写入zip文件
        with open(f'{config.文件目录}伪加密破解.zip', 'wb') as f1:
            f1.write(data)
        self.ui.print_echo.append(f"文件写入成功，请查看:{config.文件目录}伪加密破解.zip")
    except:
        self.ui.print_echo.append("伪加密破解失败")
